/**
 * 水量调度
 */
Ext.define('Admin.view.waterOptimum.waterOptimum',{
	extend: 'Ext.container.Container',
	xtype: 'waterOptimum',
	alias: 'waterOptimum',
	require: [
		'Admin.view.waterOptimum.submodule.initialConditions',
		'Admin.view.waterOptimum.submodule.schedulingChart',
		'Admin.view.waterOptimum.submodule.schedulingConstraints',
		'Admin.view.waterOptimum.submodule.schedulingPlan',
		'Admin.view.waterOptimum.resultshow.useWaterUnit',
		'Admin.view.waterOptimum.resultshow.section',
		'Admin.view.waterOptimum.resultshow.sectionSingle',
		'Admin.view.waterOptimum.resultshow.reservior',
		'Admin.view.waterOptimum.resultshow.reserviorSingle',
		'Admin.view.waterOptimum.resultshow.administrativeArea',
		'Admin.view.waterOptimum.resultshow.waterArea'
	],
	user: [],
	userCLs: 'big-100 small-100',
	layout: 'fit',
//	urlPre: 'http://localhost:8080/jsite-szy-dispatch/a/',
//	urlPre: 'http://localhost:8080/Springwap/',
	urlPre: config.URL,
//	urlSuffix: '.shtml',
	urlSuffix: '',
	schemeId: 'FH_deftest_11',
	resultSheet : [
		//	{id: 1, name: '全流域', type:1, sec:0},
		{ id: 2, name: '行政区', type: 1, sec: 1 },
		{ id: 10, name: '水资源区', type: 1, sec: 3 },
		{ id: 17, name: '用水单元', type: 1, sec: 5 },
		/*{ id: 18, name: '断面', type: 1, sec: 6 },
		{ id: 19, name: '沙子岭', type: 2, sec: 7, branch: 1 },
		{ id: 20, name: '南丰', type: 2, sec: 7, branch: 2 },
		{ id: 21, name: '南城', type: 2, sec: 7, branch: 3 },
		{ id: 22, name: '黎川', type: 2, sec: 7, branch: 4 },
		{ id: 23, name: '廖家湾', type: 2, sec: 7, branch: 5 },
		{ id: 24, name: '娄家村', type: 2, sec: 7, branch: 6 },
		{ id: 25, name: '焦石', type: 2, sec: 7, branch: 7 },
		{ id: 26, name: '李家渡', type: 2, sec: 7, branch: 8 },*/
		{ id: 27, name: '水库', type: 1, sec: 8 }
	//	{ id: 28, name: '洪门水库', type: 2, sec: 9, branch: 1 },
	//	{ id: 29, name: '廖坊水库', type: 2, sec: 9, branch: 2 }
	],
	currentView: 17,
	timeMode: 'year',	//year month xun
	river: 'fuhe',	//fuhe yuanhe
	items: [{
		xtype: 'tabpanel', // TabPanel itself has no title
		activeTab: 0,      // First tab active by default
		items: [{
			title: '初始条件',
			localId: 'tab1',
			xtype: 'woInitialConditions'
		}, {
			title: '调节方式',
			xtype: 'panel',
			localId: 'tab2',
			layout: 'fit',
			border: false,
			items: [{
				xtype: 'panel',
				layout: 'card',
				region: 'center',
				border: false,
				localId: 'adjustmentCard',
				items: [{
					xtype: 'woSchedulingChart'
				}, {
					xtype: 'woSchedulingConstraints'
				}],
				dockedItems: [{
					xtype: 'toolbar',
					dock: 'top',
					height: 50,
					items: [{
						xtype: 'button',
						localId: 'btnwoChart',
						text: '<span style="color:#000000;font-weight:bold;">►调度图</span>',
						style: 'width:120px;height:30px;background-color:#ddebf7;',
						margin: '0 20 0 10'
					}, {
						xtype: 'button',
						localId: 'btnwoGrid',
						text: '<span style="color:#000000;">调度约束</span>',
						style: 'width:120px;height:30px;background-color:#ddebf7;',
						margin: '0 20 0 0'
					}, '->', {
						xtype: 'button',
						hidden: false,
						localId: 'btnStart',
						text: '<span style="color:#FFFFFF;">调节计算</span>',
						style: 'width:120px;height:30px;background-color:#2c9eee;align:right;',
						disabled: true,
						margin: '0 20 0 0'
					}]
				}]
			}]
		}, {
			title: '调度方案',
			localId: 'tab3',
			xtype: 'woSchedulingPlan'
		}, {
			title: '结果分析',
			localId: 'tab4',
			layout: {
				type: 'hbox',
				align: 'stretch'
			},
			border: false,
			items: [{
				xtype: 'panel',
				border: false,
				width: 140,
				localId: 'resultMenuList',
				margin: '10 10 0 15',
			//	padding: '10 10 10 10',
				html: '',
				style: 'backgroundColor: #ddebf7;'
			}, {
				xtype: 'panel',
				margin: '0 10 0 0',
				layout: 'card',
				localId: 'resultPanel',
				header: false,
				title: false,
				margin: '15 10 15 5',
				activeItem: 0,
				items: [{
					html: '0 sec'
				}, {
					xtype: 'woAdministrativeArea'
				}, {
					html: '2 sec'
				}, {
					xtype: 'woWaterArea'
				}, {
					html: '4 sec'
				}, {
					xtype: 'woUseWaterUnit'
				}, {
					html: '6 sec'
					//xtype: 'woSection'
				}, {
					html: '7 sec'
					//xtype: 'woSectionSingle'
				}, {
					xtype: 'woReservior'
				}, {
					xtype: 'woReserviorSingle'
				}],
				flex: 1
			}]
		}]
	}],
	getTab: function(id){
		var tab = this.query('[localId=tab'+id+']')[0];
		return tab;
	},
	calculation: function(){
		var panel = this;
		var link = "szy/dispatch/wateroptimum/schedulingCalculation";
		
		var surl = this.urlPre + link + this.urlSuffix;

		var p = Ext.create('Ext.ProgressBar', {});

		var woWin = Ext.create('Ext.window.Window', {
		    title: '请稍候...',
		    height: 140,
		    width: 400,
		    closable: false,
		    modal : true,
		    resizable: false,
		    layout: 'border',
	    	padding:'5 15 20 15',
	    	border: false,
		    items: [{
		    	xtype: 'panel',
		    	region: 'north',
		    	html: '正在查询水库信息...',
		    	style: 'line-height:38px;font-size:16px;',
		    	height: 45,
		    	border: false
		    },{
		    	xtype:'panel',
		    	region:'center',
		    	layout: 'fit',
		    	border: false,
		    	items: p
		    }]
		}).show();
		
		var textMess = woWin.query('panel')[0];

		var task = {
			run: function() {
				if(p.getValue() < 0.9){
					p.updateProgress(p.getValue() + 0.025);
					if(p.getValue() >= 0.5)textMess.setHtml('正在计算中...');
					else if(p.getValue() >= 0.2)textMess.setHtml('正在加载供需水信息...');
				}
				else return false;
			},
			interval: 40,
			repeat: 36
		};

		Ext.TaskManager.start(task);
		
		var initData = this.query('woInitialConditions')[0].getGridDataAll();
		var constraints = this.query('woSchedulingConstraints')[0].getGridDataAll();
		
		$.ajax({
			url: surl,
			type: "post",
			data: {timeMode: panel.timeMode, initData: initData, constraints: constraints, schemeId: panel.schemeId},
			dataType: "json",
			success: function(result) {
				woShedulingResult = result;
				mainResult = woShedulingResult;
				panel.resultReady = false;
				if(result.success){
					var taskFull = {
						run: function() {
							if(p.getValue() >= 0.9){
								p.updateProgress(p.getValue() + 0.01);
								if(p.getValue() >= 1){
									woWin.close();
									panel.query('tabpanel')[0].setActiveItem(2);
									return false;
								}
								else if(p.getValue() >= 0.9)textMess.setHtml('计算完毕，正在处理显示数据...');
							}
						},
						interval: 25
					};
					Ext.TaskManager.start(taskFull);
				}
				else{
					woWin.close();
					Ext.Msg.alert('提示', result.message);
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				woWin.close();
				Ext.Msg.alert('提示', '计算时出现了错误！');
			}
		});
	},
	getResultSheet:function() {
		var output = '<div style="background-color:#ddebf7;width:100%;height:100%;border: 1px solid #ddebf7;padding: 10px 10px 10px 10px;margin: 5px 0 0 0;">';
		var resultSheet = this.resultSheet;
		for (var i = 0; i < resultSheet.length; i++) {
			if (resultSheet[i].type == 1) output += '<div sid="' + resultSheet[i].id + '" style="font-weight:bold;font-size:16px;margin:10px 0 10px 0;border-bottom: 1px solid black;cursor: pointer;">' + resultSheet[i].name + '</div>';
			else output += '<div sid="' + resultSheet[i].id + '" style="text-align: right;font-size:14px;margin:10px 0 10px 0;cursor: pointer;">' + resultSheet[i].name + '</div>';
		}
		output += '</div>';
		return output;
	},
	generateList: function(){
		var panel = this;
		var contain = this.query('panel[localId=resultMenuList]')[0];
		contain.setHtml(this.getResultSheet());
		var items = document.getElementById(contain.getId()).getElementsByTagName('div');
		for(var i=0;i<items.length;i++){
			var sid = items[i].getAttribute("sid");
			if(sid != null){
				items[i].onclick = function(obj){
					panel.changeResultView(obj.target.getAttribute("sid"));
				};
			}
		}
	},
	getListSingle: function(sid){
		var contain = this.query('panel[localId=resultMenuList]')[0];
		var items = document.getElementById(contain.getId()).getElementsByTagName('div');
		for(var i=0;i<items.length;i++){
			var id = items[i].getAttribute("sid");
			if(sid == id)return items[i];
		}
	},
	changeSectionSingleView: function(branch){

		console.log(branch);
	},
	changeReserviorSingleView: function(branch){
		this.query('woReserviorSingle')[0].changeView(branch);
	},
	changeResultView: function(sid){
		var card = this.query('panel[localId=resultPanel]')[0];
		var selectedItem;
		var resultSheet = this.resultSheet;
		for (var i = 0; i < resultSheet.length; i++) {
			if (resultSheet[i].id == sid) {
				selectedItem = resultSheet[i];
			}
		}
		var old = this.getListSingle(this.currentView);
		old.innerHTML = old.innerHTML.replace('►', '');
		
		var fresh = this.getListSingle(sid);
		fresh.innerHTML = '►' + fresh.innerHTML;
		
		this.currentView = sid;
		
		card.setActiveItem(selectedItem.sec);
		
		if(selectedItem.sec == 7){
			this.changeSectionSingleView(selectedItem.branch);
		}
		else if(selectedItem.sec == 9){
			this.changeReserviorSingleView(selectedItem.branch);
		}
	},
	initReady: false,
	consReady: false,
	initConditionData: function(){
		var link = "szy/dispatch/wateroptimum/initialCondition";
		var surl = this.urlPre + link + this.urlSuffix;
		var contain = this;
		$.ajax({
			url: surl,
			type: "post",
			data: {schemeId: contain.schemeId},
			dataType: "json",
			success: function(result) {
				contain.query('woInitialConditions')[0].displayData(result);
				contain.initReady = true;
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Ext.Msg.alert('提示', '读取初始条件时发生了错误！');
			}
		});
	},
	schedulingChart: function(){
		var link = "szy/dispatch/wateroptimum/schedulingChart";
		var surl = this.urlPre + link + this.urlSuffix;
		var contain = this;
		$.ajax({
			url: surl,
			type: "post",
			data: {schemeId: contain.schemeId},
			dataType: "json",
			success: function(result) {
				contain.query('woSchedulingChart')[0].displayData(result);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Ext.Msg.alert('提示', '读取调度图时发生了错误！');
			}
		});
	},
	schedulingConstraints: function(){
		var link = "szy/dispatch/wateroptimum/schedulingConstraints";
		var surl = this.urlPre + link + this.urlSuffix;
		var contain = this;
		$.ajax({
			url: surl,
			type: "post",
			data: {schemeId: contain.schemeId},
			dataType: "json",
			success: function(result) {
				contain.query('woSchedulingConstraints')[0].displayData(result);
				contain.consReady = true;
				contain.query('panel[localId=adjustmentCard]')[0].query('button[localId=btnStart]')[0].setDisabled(false);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Ext.Msg.alert('提示', '读取约束条件时发生了错误！');
			}
		});
	},
	resultReady: false,
	isListPanelReady: false,
	readResult: function(){
		this.resultReady = true;
		var link = "szy/dispatch/wateroptimum/schedulingResults";
		var surl = this.urlPre + link + this.urlSuffix;
		var panel = this;
		$.ajax({
			url: surl,
			type: "post",
			data: {schemeId: panel.schemeId},
			dataType: "json",
			success: function(result) {				
				if(result.index1 != null)
				panel.query('woSchedulingPlan')[0].displayData(result.index1);
				if(result.index2 != null)
				panel.query('woAdministrativeArea')[0].displayData(result.index2);
				if(result.index3 != null)	
				panel.query('woWaterArea')[0].displayData(result.index3);
				if(result.index4 != null)
				panel.query('woUseWaterUnit')[0].displayData(result.index4);
				if(result.index6 != null)
				panel.query('woReservior')[0].displayData(result.index6);
				if(result.index8 != null){
					panel.query('woReserviorSingle')[0].displayData(result.index8);
					
					if(result.index8.index1 != null){
						var freshList = [
							{ id: 1, name: '行政区', type: 1, sec: 1 },
							{ id: 2, name: '水资源区', type: 1, sec: 3 },
							{ id: 3, name: '用水单元', type: 1, sec: 5 },
							{ id: 4, name: '水库', type: 1, sec: 8 }
						];
						
						for(var i=0;i<result.index8.index1.length;i++){
							freshList.push({ id: 5+i, name: result.index8.index1[i]+'水库', type: 2, sec: 9, branch: i+1 });
						}
						
						panel.resultSheet = freshList;
						panel.currentView = 3;
					}					
					
					if(panel.isListPanelReady){
						panel.generateList();
						panel.changeResultView(panel.currentView);
					}
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Ext.Msg.alert('提示', '读取调度结果时发生了错误！');
			}
		});
	},
	testLink:function(){
		var link = "szy/dispatch/wateroptimum/test";
		var surl = this.urlPre + link + this.urlSuffix;
		var contain = this;
		$.ajax({
			url: surl,
			type: "post",
			data: {timeMode: contain.timeMode},
			dataType: "json",
			success: function(result) {
				console.log(result);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				Ext.Msg.alert('提示', '读取初始条件时发生了错误！');
			}
		});
	},
	eventBind: function(){
		var panel = this;
		this.initConditionData();
		this.testLink();
		this.getTab(2).on({
			boxready: {
				fn: function(obj, width, height, eOpts){
					var panelAdjustmentCard = this.query('panel[localId=adjustmentCard]')[0];
					var btnWOChart = panelAdjustmentCard.query('button[localId=btnwoChart]')[0];
					var btnWOGrid = panelAdjustmentCard.query('button[localId=btnwoGrid]')[0];
					btnWOChart.on({
						click:{
				        	fn: function(obj, e, eOpts){
				        		panelAdjustmentCard.setActiveItem(0);
				        		btnWOChart.setText('<span style="color:#000000;font-weight:bold;">►调度图</span>');
				        		btnWOGrid.setText('<span style="color:#000000;">调度约束</span>');
				            }
				        }
					});
					btnWOGrid.on({
						click:{
				        	fn: function(obj, e, eOpts){
				        		panelAdjustmentCard.setActiveItem(1);
				        		btnWOChart.setText('<span style="color:#000000;">调度图</span>');
				        		btnWOGrid.setText('<span style="color:#000000;font-weight:bold;">►调度约束</span>');
				            }
				        }
					});
					panelAdjustmentCard.query('button[localId=btnStart]')[0].on({
						click:{
				        	fn: function(obj, e, eOpts){
				        		panel.calculation();
				        		/*if(panel.initReady && panel.consReady){
				        			
				        		}
				        		else{
				        			Ext.Msg.alert('提示信息', '初始条件和约束条件尚未读取完毕，请稍后再试！', function(){});
				        		}*/
				            }
				        }
					});
					
				}
			}
		});
		this.query('woSchedulingChart')[0].on({
			boxready: {
				fn: function(obj, width, height, eOpts){
					panel.schedulingChart();
				}
			}
		});
		this.query('woSchedulingConstraints')[0].on({
			boxready: {
				fn: function(obj, width, height, eOpts){
					panel.schedulingConstraints();
				}
			}
		});
		this.query('tabpanel')[0].on({
			tabchange: {
				fn: function( tabPanel, newCard, oldCard, eOpts ) {
					if(newCard.localId == 'tab3' || newCard.localId == 'tab4'){
						if(!panel.resultReady)panel.readResult();
					}
				}
			}
		});
		this.getTab(4).on({
			boxready: {
				fn: function(obj, width, height, eOpts){
					panel.isListPanelReady = true;
					panel.generateList();
					panel.changeResultView(panel.currentView);
				}
			}
		});
		
	},
	parentSchemeId: function(){
		var idle = null;
		try{
			idle = $.dispatch.getProCd();
		}catch(e){
			Ext.Msg.alert('提示信息', '无法读取方案ID信息');
		}
		if(idle != null){
			this.schemeId = idle;var text = idle + '                  ';
			this.schemeId = text.substring(0,13);
		}
		else{			
			Ext.Msg.alert('提示信息', '方案号设置不合理！');
		}
	},
	listeners: {
		boxready: {
			fn: function(){
				this.parentSchemeId();
				this.eventBind();
			}
		}
	}
});